package com.ai.dtcore.control;

import java.lang.reflect.Method;
import java.util.Map;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.dao.DataAccessException;

import com.ai.common.xml.util.ControlConstants;
import com.ai.dtcore.util.MyOwnRuntimeException;
import com.ai.dtcore.util.StringUtil;
import com.ai.dtcore.util.Constants.MQ_TOPIC;
import com.ai.frame.IControlService;
import com.ai.frame.bean.InputObject;
import com.ai.frame.bean.OutputObject;
import com.ai.frame.logger.Logger;
import com.ai.frame.logger.LoggerFactory;
import com.ai.frame.util.JsonUtil;

/**
 */
public class ControlServiceImpl implements IControlService, BeanFactoryAware {
	private static final Logger logger = LoggerFactory
			.getApplicationLog(ControlServiceImpl.class);

	private BeanFactory factory;

	public void setBeanFactory(BeanFactory factory) {
		this.factory = factory;
	}

	public String execute(String json) {
		InputObject inObj = null;
		OutputObject outObj = new OutputObject();
		long start = System.currentTimeMillis();
		try {
			inObj = JsonUtil.json2InputObject(json);
			outObj.setReturnCode(ControlConstants.RETURN_CODE.IS_OK);
			if (inObj != null) {
				String logParam = "OP_REQST_NO=" + inObj.getLogParams().get("OP_REQST_NO")  + ",service=" + inObj.getService() + ", method=" + inObj.getMethod();
				logger.info("INVOKE START!", logParam);
				Object object = factory.getBean(inObj.getService());
				Method mth = object.getClass().getMethod(inObj.getMethod(), InputObject.class, OutputObject.class);
				mth.invoke(object, inObj ,outObj);
				
				logger.info("INVOKE SECCESS!", logParam + ", COST="+(System.currentTimeMillis() - start)+"ms");
			} else {
				throw new MyOwnRuntimeException("InputObject can't be null !!!");
			}
		} catch (Exception e) {
			if (inObj != null && inObj.getLogParams() != null && StringUtil.isNotEmpty(inObj.getLogParams().get("OP_REQST_NO"))) {
				String logParam = "OP_REQST_NO=" + inObj.getLogParams().get("OP_REQST_NO")  + ",service=" + inObj.getService() + ", method=" + inObj.getMethod();
				logger.error("execute INVOKE ERROR! ", logParam + ",  JSON = "+ json , e);
			} else {
				logger.error("execute INVOKE ERROR! ", "JSON = "+ json, e);
			}
			// 异常处理
			outObj.setReturnCode(ControlConstants.RETURN_CODE.SYSTEM_ERROR);
			if(e.getCause() instanceof DataAccessException){
                outObj.setReturnMessage("数据操作失败!");
            }else {
                outObj.setReturnMessage(e.getMessage() == null ? e.getCause().getMessage() : e.getMessage());
            }
		} finally{
			//saveUserOperLog(start, System.currentTimeMillis(), inObj, outObj);
		}
		return JsonUtil.outputObject2Json(outObj);
	}
	
	/**
	 * 记录操作日志
	 * 
	 * @param startTime
	 *            开始时间
	 * @param endTime
	 *            结束时间
	 * @param inputObject
	 *            入参
	 *            </br>logParam中存放公用信息，如用户信息
	 *            </br>params存放参数信息
	 * @param outputObject
	 *            出参
	 */
	public void saveUserOperLog(long startTime, long endTime, InputObject inObj, OutputObject outObj) {
		if("saveOperLog".equals(inObj.getMethod()) || StringUtil.isEmpty("LOGIN_LG_ID")){
			return;
		}
		System.out.println("开始记录日志");
		try {
			long duringMs = endTime - startTime;
			Map<String, String> logMap = inObj.getLogParams();
			logMap.put("OP_TYPE_CD", "1");
			logMap.put("duringMs", String.valueOf(duringMs));
			logMap.put("INVK_SRV_NM", inObj.getService());
			logMap.put("INVK_MTHD_NM", inObj.getMethod());
			logMap.put("OP_RSLT_CD", outObj.getReturnCode());
			logMap.put("BACKTO_RSLT_CNTT", outObj.getReturnMessage());
			String param = JsonUtil.convertObject2Json(inObj.getParams());
			if (StringUtil.isNotEmpty(param) ) {
				logMap.put("REQST_PARA_CNTT", param);
			}
			
			logMap.put("OP_SRC_CD", "2");
			InputObject inputObject = new InputObject("userService", "saveOperLog", logMap);
			Object object = factory.getBean("queueService");
			Method mth = object.getClass().getMethod("sendMsg2MQ", String.class,String.class, InputObject.class);
			System.out.println(mth.invoke(object, MQ_TOPIC.TOPIC_OPER_LOG ,logMap.get("LOGIN_LG_ID"), inputObject));
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("saveUserOperLog", "批量记录操作日志失败!", e);
		}
	}
}
